package com.chocus.core.service.buyer;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.chocus.common.web.Constants;
import com.chocus.core.bean.BuyerCart;
import com.chocus.core.bean.BuyerItem;
import com.chocus.core.bean.order.Detail;
import com.chocus.core.bean.order.Order;
import com.chocus.core.bean.product.Sku;
import com.chocus.core.bean.user.Buyer;
import com.chocus.core.bean.user.BuyerQuery;
import com.chocus.core.dao.order.DetailDao;
import com.chocus.core.dao.order.OrderDao;
import com.chocus.core.dao.product.ColorDao;
import com.chocus.core.dao.product.ProductDao;
import com.chocus.core.dao.product.SkuDao;
import com.chocus.core.dao.user.BuyerDao;

import redis.clients.jedis.Jedis;

@Service("buyerService")
public class BuyerServiceImpl implements BuyerService {

	@Autowired
	private BuyerDao buyerDao;
	@Autowired
	private SkuDao skuDao;
	@Autowired
	private ProductDao productDao;
	@Autowired
	private ColorDao colorDao;
	@Autowired
	private OrderDao orderDao;
	@Autowired
	private DetailDao detailDao;
	@Autowired
	@Qualifier("jedis")
	private Jedis jedis;

	/**
	 * 通过用户名查询用户
	 * 
	 * @param username
	 * @return
	 */
	public Buyer getBuyerByUsername(String username) {
		BuyerQuery buyerQuery = new BuyerQuery();
		buyerQuery.createCriteria().andUsernameEqualTo(username);
		List<Buyer> buyers = buyerDao.selectByExample(buyerQuery);
		if (buyers != null && buyers.size() > 0) {
			return buyers.get(0);
		}
		return null;
	}

	/**
	 * 将购物车商品保存到redis
	 * 
	 * @param buyerCart
	 * @param username
	 */
	@Override
	public void addBuyerCartToRedis(BuyerCart buyerCart, String username) {
		// TODO Auto-generated method stub
		if (buyerCart != null) {
			List<BuyerItem> items = buyerCart.getItems();
			if (items != null && items.size() > 0) {
				for (BuyerItem buyerItem : items) {
					if (jedis.hexists(Constants.BUYER_CART + ":" + username,
							String.valueOf(buyerItem.getSku().getId()))) {
						jedis.hincrBy(Constants.BUYER_CART + ":" + username, String.valueOf(buyerItem.getSku().getId()),
								1);
					} else {
						jedis.hset(Constants.BUYER_CART + ":" + username, String.valueOf(buyerItem.getSku().getId()),
								String.valueOf(buyerItem.getAmount()));
					}
				}
			}
		}
	}

	/**
	 * 从redis中获取购物车对象
	 * 
	 * @param username
	 * @return
	 */
	@Override
	public BuyerCart getBuyerCartFromRedis(String username) {
		// TODO Auto-generated method stub
		Map<String, String> map = jedis.hgetAll(Constants.BUYER_CART + ":" + username);
		Set<Entry<String, String>> entrySet = map.entrySet();
		BuyerCart buyerCart = new BuyerCart();
		if (map != null) {
			for (Entry<String, String> entry : entrySet) {
				BuyerItem buyerItem = new BuyerItem();
				buyerItem.setAmount(Integer.parseInt(entry.getValue()));
				Sku sku = new Sku();
				sku.setId(Long.parseLong(entry.getKey()));
				buyerItem.setSku(sku);
				buyerCart.setItem(buyerItem);
			}
		}
		return buyerCart;
	}

	/**
	 * 向购物车中填充数据
	 * 
	 * @param buyerCart
	 */
	@Override
	public Sku putDataToBuyerCart(BuyerItem buyerItem) {
		Sku sku = new Sku();
		// 商品id 名称 图片 颜色 数量 。。。
		if (buyerItem.getSku() != null) {
			Long skuId = buyerItem.getSku().getId();
			sku = skuDao.selectByPrimaryKey(skuId);
			if (sku != null) {
				// 商品对象
				sku.setProduct(productDao.selectByPrimaryKey(sku.getProductId()));
				// 颜色对象
				sku.setColor(colorDao.selectByPrimaryKey(sku.getColorId()));
			}
		}
		return sku;
	}

	/**
	 * 保存订单及订单详情并清空购物车
	 * 
	 * @param order
	 * @param username
	 */
	@Transactional
	public void saveOrder(Order order, String username) {
		// 取出购物的车
		BuyerCart buyerCart = getBuyerCartFromRedis(username);
		List<BuyerItem> items = buyerCart.getItems();
		for (BuyerItem buyerItem : items) {
			buyerItem.setSku(putDataToBuyerCart(buyerItem));
		}
		// 保存订单
		// ID或订单号
		Long id = jedis.incr("oid");
		order.setId(id);
		// 运费
		order.setDeliverFee(buyerCart.getFee());
		// 应付金额
		order.setTotalFee(buyerCart.getTotal());
		// 订单金额
		order.setOrderPrice(buyerCart.getPrice());
		// 支付状态 :0到付1待付款,2已付款,3待退款,4退款成功,5退款失败
		if (order.getPaymentWay() == 0) {
			order.setIsPaiy(0);
		} else {
			order.setIsPaiy(1);
		}
		// 订单状态 0:提交订单 1:仓库配货 2:商品出库 3:等待收货 4:完成 5待退货 6已退货
		order.setOrderState(0);
		// 订单生成时间
		order.setCreateDate(new Date());
		// 用户名
		order.setBuyerId(username);
		orderDao.insertSelective(order);
		// 保存订单详情
		for (BuyerItem buyerItem : items) {
			Detail detail = new Detail();
			// 订单ID
			detail.setOrderId(id);
			// 商品编号
			detail.setProductId(buyerItem.getSku().getProduct().getId());
			// 商品名称
			detail.setProductName(buyerItem.getSku().getProduct().getName());
			// 颜色名称
			detail.setColor(buyerItem.getSku().getColor().getName());
			// 尺码
			detail.setSize(buyerItem.getSku().getSize());
			// 商品销售价
			detail.setPrice(buyerItem.getSku().getPrice());
			// 购买数量
			detail.setAmount(buyerItem.getAmount());
			detailDao.insertSelective(detail);
		}
		// 清空购物车
		jedis.del(Constants.BUYER_CART + ":" + username);
	}
}
